"""
本实例为单例模式下的flask创建实例帮助类
"""
import json
import logging
import os
from logging.handlers import RotatingFileHandler

from flask import Flask

from air_web.config.config import app_conf, config
from air_web.web_flask.common.extensions import cors


class FlaskHelper(object):
    _flask_app = None

    @classmethod
    def create_app(cls, config_name="development"):
        if cls._flask_app is None:
            cls._flask_app = Flask("gate")
            cls._flask_app.config.from_object(app_conf[config_name])
            cls.register_logger()
            cls.register_extensions()
            cls.write_es_auth_to_env()
        return cls._flask_app

    @staticmethod
    def write_es_auth_to_env():
        """es用户名密码写入环境变量，ruleng会使用"""
        es_auth = {"http_auth": (config["ES_USER"], config["ES_PASSWORD"])}
        os.environ.update({"ZS_ES_EXTRA_ARGS": json.dumps(es_auth)})

    @classmethod
    def register_logger(cls):
        cls._flask_app.logger.setLevel(logging.INFO)

        formatter = logging.Formatter(
            "[%(asctime)s] %(levelname)s in %(funcName)s(%(filename)s:%(lineno)d): %(message)s"
        )
        file_handler = RotatingFileHandler(
            "/home/smxu/PycharmProjects/websvr/gate/src/logs/gate.log",
            maxBytes=10 * 1024 * 1024,
            backupCount=10,
        )
        # file_handler = RotatingFileHandler(basedir + '/logs/gate.log',
        #                                    maxBytes=10 * 1024 * 1024, backupCount=10)
        file_handler.setFormatter(formatter)

        if not cls._flask_app.debug:
            cls._flask_app.logger.addHandler(file_handler)

    @classmethod
    def register_extensions(cls):
        cors.init_app(cls._flask_app)
        # db.init_app(app)
